/*
 * @Description: 跳转方法封装
 * @version: 1.0.0
 * @Author: Rattenking
 * @Date: 2022-10-18 10:25:31
 * @LastEditors: Rattenking
 * @LastEditTime: 2022-10-18 10:32:33
 */
import Taro from "@tarojs/taro";

const NAVIGATION_TYPES = {
  NAVIGATE_TO: 'navigateTo',
  SWITCH_TAB: 'switchTab',
  RE_LAUNCH: 'reLaunch',
  REDIRECT_TO: 'redirectTo',
  NAVIGATE_BACK: 'navigateBack'
};

const validateNavigationOptions = (options) => {
  if (!options.url && !options.delta) {
    throw new Error('Either url or delta must be provided');
  }
};

const routeTo = (options) => {
  try {
    validateNavigationOptions(options);
    $route({ ...options, type: options.type || NAVIGATION_TYPES.NAVIGATE_TO });
  } catch (error) {
    console.error('Navigation error:', error);
  }
};

/**
 * 1. 判断传入url是否有效
 * 2. 判断是小程序路径还是外部H5
 * 3. 判断是返回还是直接为空字符串
 * */
const handleExternalUrl = (url, type) => {
  if (api.hasWeapp()) {
    Taro.setStorageSync('urlAndParams', `${url}`);
    const targetPage = url.indexOf('islogin=1') > -1 
      ? '../../pages/payLogin/index'
      : '../../pages/pay/index';
    route({ url: targetPage, type });
  } else {
    window.location.href = url;
  }
};

const $route = (options) => {
  const { type = NAVIGATION_TYPES.NAVIGATE_TO, url = '', delta } = options;

  if (url) {
    const isExternalUrl = url.indexOf('http') > -1;
    isExternalUrl ? handleExternalUrl(url, type) : route(options);
  } else if (delta) {
    Taro.navigateBack(options);
  }
};

const route = (options) => {
  const { type = NAVIGATION_TYPES.NAVIGATE_TO, url } = options;
  const navigationType = NAVIGATION_TYPES[type] || NAVIGATION_TYPES.NAVIGATE_TO;
  Taro[navigationType]({ url });
};

export default {
  routeTo,
  $route,
};